/*
 * @Author: tcosfish
 * @Date: 2022-07-21 10:16:13
 * @LastEditors: tcosfish
 * @LastEditTime: 2022-08-19 17:00:12
 * @FilePath: \loadFile\src\routes\user\user.route.ts
 */

import Router from "koa-router"

import * as path from "path"
import * as fs from "fs"

import { is_exists_file, get_file_ext } from "utils/upload_file_funs"
import { create_month_report_2 } from "@/features/month.create.2"
import { read_month_repo } from "@/excel"
import { subOperation } from "@/database/feat/sub-operation"
import { createMonthlyReport } from "@/excel/feat/create_month_repo"

import { fillTemplate } from "@/excel/feat/fill_template"
import { outputRuntime } from "@/utils/runtimeAlert"
import RyExcel from "@/excel/RyExcel"
import { RecordView } from "@/database/views/Record.view"
import { shortPath } from "@/utils/shortPath"

const user_routers = new Router()

user_routers.prefix("/user")

// 测试案例一
user_routers.get("/", async (ctx) => {
  ctx.body = `<h1>This is user/ response</h1>`
})

// TODO 用户文件上传
user_routers.post("/uploads", async (ctx) => {
  console.log(ctx.request.body) // 文件和相关信息都拿到了
  const files = ctx.request.files
  if (files !== undefined) {
    ctx.type = "application/json"
    ctx.body = JSON.stringify({
      code: 200,
      message: "request success!",
      file: {},
    })
  } else {
    ctx.type = "application/json"
    ctx.body = JSON.stringify({
      code: 208,
      message: "文件上传但是并没被获取",
    })
  }
})

// TODO 用户指定文件下载
user_routers.get("/download/:filename", async (ctx) => {
  const filename = ctx.params.filename
  const ext = get_file_ext(filename)
  const filepath = path.join(
    __dirname,
    `../../../public/uploads/${ext}/${filename}`
  )

  if (is_exists_file(filepath)) {
    ctx.response.header["content-type"] = "application/octet-stream" // 表明为二进制文件
    ctx.response.header[
      "content-disposition"
    ] = `attachment; filename=${encodeURI(filename)}`
    ctx.body = fs.createReadStream(filepath)
  } else {
    ctx.response.header["content-type"] = "application/json"
    ctx.status = 404
    ctx.body = JSON.stringify({
      msg: "路径所求文件不存在",
    })
  }
})

// 月报生成 - 2.损益表/科目余额表/成本费用明细生成
user_routers.get("/month-report.2", async (ctx) => {
  // 创建月报的科目余额相关的内容
  create_month_report_2()
})

//
user_routers.get("/month.test", async (ctx) => {
  // * 1. 从上传的文件中获取数据
  const month_repo_path = path.join(
    __dirname,
    "../../../",
    "public/uploads/xls/科目 余额  003  .xls"
  )
  // const values = read_month_repo(month_repo_path)
  // values.pop() // 抛出合计行

  // * 2. 将读取到的内容利用 typeORM 存放到数据库中
  // 已OK, 但最近最后一行的合计不具有 code 属性, 我建议不录入
  // subOperation(values[0])

  // * 2.1 筛选数据
  // const result = await getData()
  // const result = await filterData()
  // console.dir(result)

  // * 3. 筛选数据, 并使用 exceljs 生成处理后的 xlsx 文件
  // const data = result.map((row: any) => Object.values(row))

  const save_filepath = path.join(
    __dirname,
    "../../../",
    "public/uploads/xlsx/demo.test.xlsx"
  )
  // create_month_repo(data, save_filepath)

  ctx.type = "application/json"
  ctx.body = {
    status: 200,
    message: "接口相关内容已执行完毕",
  }
})

// 测试: 基本月报生成(无数据)
user_routers.get("/database.test", async (ctx) => {
  console.time("createMonthlyReportTime")
  const save_filepath = path.join(
    __dirname,
    "../../../",
    "public/uploads/xlsx/demo3.test.xlsx"
  )
  outputRuntime(
    "基本月报生成",
    async () => await createMonthlyReport(save_filepath)
  )
  ctx.type = "application/json"
  ctx.body = {
    status: 200,
    message: "接口相关内容已执行完毕",
  }
})

// 测试: 损益表模板填写
user_routers.get("/fillIncome.test", async (ctx) => {
  const save_filepath = path.join(
    __dirname,
    "../../../",
    "public/uploads/xlsx/fillIncome.test.xlsx"
  )
  outputRuntime("填充测试", () => fillTemplate("损益表", 1, 4, save_filepath))
  ctx.type = "application/json"
  ctx.body = {
    status: 200,
    message: "接口相关内容已执行完毕",
  }
})

// 测试: 预算表模板填写
user_routers.get("/fillBudget.test", async (ctx) => {
  const save_filepath = path.join(
    __dirname,
    "../../../",
    "public/uploads/xlsx/fillBudget.test.xlsx"
  )
  outputRuntime("预算表填充测试", () =>
    fillTemplate("预算表", 2, 5, save_filepath)
  )
  ctx.type = "application/json"
  ctx.body = {
    status: 200,
    message: "接口相关内容已执行完毕",
  }
})

// 测试: 读取上传的科目余额.xls
user_routers.get("/readUploadFile.test", async (ctx) => {
  const month_repo_path = path.join(
    __dirname,
    "../../../",
    "public/uploads/xls/科目余额.xls"
  )
  outputRuntime("将科目余额的文件存入数据库", () => {
    const values = read_month_repo(month_repo_path)
    values[0].pop()
    subOperation(values[0])
  })
  ctx.type = "application/json"
  ctx.body = {
    status: 200,
    message: "接口相关内容已执行完毕",
  }
})

// 测试: 读取上传的分录.xls
user_routers.get("/readRecordFile.test", async (ctx) => {
  // // const month_repo_path = shortPath("分录", "xls")
  const save_filepath = shortPath("fillRecord.test", "xlsx")
  const templatePath = shortPath("资金动态表模板", "xlsx", "/template/")
  // // const header: string[] = ["", "code", "name", "debit", "credit", ""]
  outputRuntime("生成资金动态表", async () => {
    // 1. 读取分录文件
    // const values = read_month_repo(month_repo_path, header)
    // 2. 将数据存入数据库中
    // insertData(values, Record)
    // 3. 填写资金动态模板
    // // fillTemplateByRecord("资金动态表", 2, 4, save_filepath)
    await RyExcel.createTemplate()
      .addSheet(`1. 资金动态表`)
      .copy(templatePath, "Sheet1", 1)
    await RyExcel.fill(2, 4, { entity: RecordView })
    await RyExcel.saveFile(save_filepath)
  })
  ctx.type = "application/json"
  ctx.body = {
    status: 200,
    message: "接口相关内容已执行完毕",
  }
})

export default user_routers
